use super::*;

pub struct Message
{
    msgs: [Msg; 1024],
}
struct Msg
{
    check: u16,
    handle: fn(&[u8], usize),
    callback: usize,
}
fn handle_and_callback<T: NetSer>(buf: &[u8], callback: usize)
{
    unsafe {
        let function = std::mem::transmute::<usize, fn(&T)>(callback);
        let msg = std::mem::zeroed::<T>();
        function(&msg);
    }
}
impl Message
{
    pub fn bind<T: NetSer>(&mut self, callback: fn(&T))
    {
        let id = T::get_id();
        self.msgs[id as usize].check = T::get_check();
        self.msgs[id as usize].handle = handle_and_callback::<T>;
        self.msgs[id as usize].callback = callback as usize;
    }
    pub fn handle(&mut self, buf: &[u8])
    {
        unsafe {
            let id = *(buf.as_ptr() as *const u16);
            let check = *(buf.as_ptr() as *const u16);
            if self.msgs[id as usize].check == check
            {
                (self.msgs[id as usize].handle)(buf, self.msgs[id as usize].callback);
            }
            else
            {
                eprintln!("网络消息效验失败 消息ID={} 正确check={} 接收check={}", id, self.msgs[id as usize].check, check);
            }
        }
    }
}
